<template>
  <div class="burger-fold-panel-item">
    <div
      class="burger-fold-panel-item-header"
      :class="visible ? 'no-bottom' : ''"
      @click="handleClick"
    >
      <slot name="title">
        <span>{{ title }}</span>
      </slot>
      <img
        class="arrow"
        :class="open ? 'down' : ''"
        src="../../assets/icon/arrow-right.svg"
        alt="arrow-right"
        width="16"
      />
    </div>
    <div v-show="visible" ref="wrap" class="burger-fold-panel-item-wrap">
      <div class="burger-fold-panel-item-content">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'FoldPanelItem',
};
</script>

<script setup lang="ts">
import { computed, inject, onMounted, ref, watch, watchEffect } from 'vue';
import { FoldPanelProps } from '../types';

const props = defineProps({
  name: {
    type: [String, Number],
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['change']);

const wrap = ref<HTMLDivElement | null>();

const visible = ref(true);

const foldPanelProps = inject<FoldPanelProps>('foldPanelProps');

const handleChange = inject<Function>('handleChange');

const activeFlag = computed(() => {
  // 如果是手风琴模式，则只显示一个
  if (foldPanelProps?.accordion) {
    return foldPanelProps?.modelValue === props.name;
  } else {
    // 如果是非手风琴模式，则显示所有
    if (Array.isArray(foldPanelProps?.modelValue)) {
      return (
        foldPanelProps?.modelValue.findIndex((item) => item === props.name) > -1
      );
    } else {
      return foldPanelProps?.modelValue === props.name;
    }
  }
});

const toggleVisible = () => {
  visible.value = false;
  wrap.value?.removeEventListener('transitionend', toggleVisible);
  if (handleChange) {
    handleChange({ name: props.name, visible: visible.value });
  }
};

const open = ref(false);

const handleClick = () => {
  open.value = !open.value;
  if (!visible.value) {
    visible.value = true;
    requestAnimationFrame(() => {
      if (wrap.value) {
        wrap.value.style.height = `${height.value}px`;
      }
    });
    if (handleChange) {
      handleChange({ name: props.name, visible: visible.value });
    }
  } else {
    if (wrap.value) {
      wrap.value.style.height = `0`;
    }
    wrap.value?.addEventListener('transitionend', toggleVisible);
  }
};

const height = ref(0);

onMounted(() => {
  // @ts-ignore
  height.value = wrap.value?.getBoundingClientRect().height;
  visible.value = !!activeFlag.value;
  open.value = !!activeFlag.value;
  if (wrap.value) {
    wrap.value.style.height = !activeFlag.value ? `0` : `${height.value}px`;
  }
});
</script>

<style lang="less" scoped>
@import url(./index.less);
</style>
